#!/usr/bin/env python
# -*- coding:utf-8 -*-

from spire.presentation import Presentation, IShape, ShapeType, SlidePicture, PictureShape, ITable, IAutoShape


def ppt_structure_parser(target_file):
    # 创建一个Presentation实例
    presentation = Presentation()
    presentation.LoadFromFile(target_file)

    # 遍历每一页幻灯片
    slide_info = []
    for slide_index, slide in enumerate(presentation.Slides):
        # 初始化统计信息
        text_count = 0
        image_count = 0
        table_count = 0
        elements_info = []

        # 遍历幻灯片中的每个形状
        for shape in slide.Shapes:
            if isinstance(shape, IAutoShape) and shape.TextFrame.Text:
                text_count += 1
                text_content = shape.TextFrame.Text
                elements_info.append({"type": "TextBox", "instance": IAutoShape,  "shape": shape, "content": text_content})

            elif isinstance(shape, SlidePicture):
                image_count += 1
                elements_info.append({"type": "Image", "instance": SlidePicture, "shape": shape, "content": shape.Name})

            elif isinstance(shape, PictureShape):
                image_count += 1
                elements_info.append({"type": "Image", "instance": PictureShape, "shape": shape, "content": None})

            elif isinstance(shape, ITable):
                table_count += 1
                elements_info.append({"type": "Table", "instance": ITable, "shape": shape, "content": None})

        # 汇总当前幻灯片的信息
        slide_data = {
            "slide_number": slide_index + 1,
            "text_boxes": text_count,
            "images": image_count,
            "tables": table_count,
            "elements": elements_info
        }
        slide_info.append(slide_data)

    presentation.Dispose()

    return slide_info


if __name__ == '__main__':
    # 使用函数分析PPT文件
    ppt_file = r"C:\programs\python\ai_projects\PPT_EA\backend\upload\templates\template1.pptx"
    ppt_structure = ppt_structure_parser(ppt_file)

    # 打印结构化结果
    for slide in ppt_structure:
        print(f"\n第 {slide['slide_number']} 页:")
        print(f" - 文本框数量: {slide['text_boxes']}")
        print(f" - 图片数量: {slide['images']}")
        print(f" - 表格数量: {slide['tables']}")
        for element in slide["elements"]:
            print(f"   元素: {element}")

    print("\n分析完成！")